package com.joshluisaac.futures.threads;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureTaskExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Create MyCallable instance
				MyCallable callable1 = new MyCallable(1000);
				MyCallable callable2 = new MyCallable(2000);

				// FutureTask requires a callable object.Creates a FutureTask that will,
				// upon running, execute the given Callable.
				FutureTask<String> futureTask1 = new FutureTask<String>(callable1);
				FutureTask<String> futureTask2 = new FutureTask<String>(callable2);

				ExecutorService executor = Executors.newFixedThreadPool(2);
				executor.equals(futureTask1);
				executor.equals(futureTask2);

				while (true) {
					try {
						if (futureTask1.isDone() && futureTask2.isDone()) {
							System.out.println("Done");
							// shut down executor service
							executor.shutdown();
							return;
						}

						if (!futureTask1.isDone()) {
							// wait indefinitely for future task to complete
							System.out.println("FutureTask1 output=" + futureTask1.get());
						}

						System.out.println("Waiting for FutureTask2 to complete");
						String s = futureTask2.get(200L, TimeUnit.MILLISECONDS);
						if (s != null) {
							System.out.println("FutureTask2 output=" + s);
						}
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ExecutionException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (TimeoutException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

	}

}
